package pub.cleangao.masc.runtime;


import lombok.Data;
import pub.cleangao.masc.util.PropertiesLoader;

import java.util.Properties;


@Data
public class RpcConfigProperties {


    static final String CONFIG_PROPERTIES = "rpc.properties";

    public static RpcConfigProperties init() {
        Properties properties = PropertiesLoader.loadFrom(CONFIG_PROPERTIES);
        if (properties != null) {
            RpcConfigProperties configProperties = new RpcConfigProperties();
            String registryUrl = properties.getProperty("rpc.registry.url", "");
            configProperties.setRegistryUrl(registryUrl.trim());
            String registryUsername = properties.getProperty("rpc.registry.username", null);
            configProperties.setRegistryUsername(registryUsername);
            String registryPassword = properties.getProperty("rpc.registry.password", null);
            configProperties.setRegistryPassword(registryPassword);
            setDefaultValues(configProperties);
            return configProperties;
        }
        throw new RuntimeException("Classpath not found config file: rpc.properties");
    }

    private static void setDefaultValues(RpcConfigProperties properties) {
        if (properties.getRegistryUrl() == null || properties.getRegistryUrl().isBlank()) {
            throw new IllegalArgumentException("Config etcd-server url must be set.");
        }
        if (properties.getRegistryUsername() != null && properties.getRegistryUsername().isBlank()) {
            properties.setRegistryUsername(null);
        }
        if (properties.getRegistryPassword() != null && properties.getRegistryPassword().isBlank()) {
            properties.setRegistryPassword(null);
        }
    }


    /**
     * server:port 使用英文逗号分割
     */
    private String registryUrl;

    /**
     * 用户密码
     */
    private String registryPassword;

    /**
     * 用户名
     */
    private String registryUsername;


}
